package com.lirh.mywebsocket.socketimpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lirh.mywebsocket.vo.SocketMsg;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * spirngboot+websocket实现聊天室（单聊+多聊）
 */

@Component
@ServerEndpoint("/websocket/{nickname}")
public class MyWebSocket {
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet=new CopyOnWriteArraySet<>();
    private static Map<String,Session> map=new HashMap<>();

    private Session session;
    private String name;
    @OnOpen
    public void onOpen(Session session, @PathParam("nickname")String nickname){
        this.name=nickname;
        this.session=session;

        map.put(session.getId(),session);

        webSocketSet.add(this);
        System.out.println("有新连接加入，当前在线人数为"+webSocketSet.size());
        this.session.getAsyncRemote().sendText("恭喜"+nickname+"成功连接上Websocket(其频道号："+session.getId()+" )-->当前在线人数"+webSocketSet.size());
    }
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        System.out.println("有一连接关闭！当前在线人数为"+webSocketSet.size());
    }
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端的消息："+name+": "+message);

        //转换消息为socketMsg对象
        ObjectMapper objectMapper=new ObjectMapper();
        SocketMsg socketMsg;
        try {
            socketMsg=objectMapper.readValue(message,SocketMsg.class);
            if (socketMsg.getType()==1){
                //单聊，需要找到发送哲和接收者
                socketMsg.setFromUser(session.getId());
                Session toSession = map.get(socketMsg.getToUser());
                if (toSession!=null){
                    //发送给发送者
                    session.getAsyncRemote().sendText(name+": "+socketMsg.getMsg());
                    toSession.getAsyncRemote().sendText(name+": "+socketMsg.getMsg());
                }else {
                  session.getAsyncRemote().sendText("系统消息，对方不在线或者您输入的频道号不对");
                }
            }else {
                //群发消息
                broadccast(name+": "+socketMsg.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //群发消息 TODO
//        broadccast(name+": "+message);
    }
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    private void broadccast(String message){
        webSocketSet.stream().forEach(s->{
            s.session.getAsyncRemote().sendText(message);
        });
    }

}
